#!/bin/sh

# janus script edited by Tim Riker <Tim@Rikers.org>

echo "From janus $1"

[ -z "$1" ] && { 
	echo "Error: should be called from janus"
	exit 1 
}

export LD_LIBRARY_PATH=LD_LIBRARY_PATH:/opt/janus/lib/sys

REC_BIN="/opt/janus/bin/lms-pp-rec"
FFMPEG_BIN="/opt/janus/bin/ffmpeg"
DEST_DIR="/opt/janus/share/janus/combine"

VIDEO_SUBFIX=".none"

[ -z "$dir" ] && { 
	echo "Error: no parameter dir"
	exit 1 
}

[ -z "$filename" ] && { 
	echo "Error: no parameter filename"
	exit 1 
} 

[ -z "$video_codec" ] && {
	echo "Error: no parameter video_codec"
	exit 1 
}

[ -z "$audio_codec" ] && {
	echo "Error: no parameter audio_codec"
	exit 1 
}

[ -d "$dir" ] || { 
	echo "Error: no $dir"
	exit 1
}

[ -x "$REC_BIN" ] || {
	echo "Error: no $REC_BIN"
	exit 1
}

[ -x "$FFMPEG_BIN" ] || {
	echo "Error: no $FFMPEG_BIN"
	exit 1
}

[ -f "$dir/$filename-audio.mjr" ] || {
	echo "Error: no $dir/$filename-audio.mjr"
	exit 1
}

[ -f "$dir/$filename-video.mjr" ] || {
	echo "Error: no $dir/$filename-video.mjr"
	exit 1
}

if [ "$video_codec" != "h264" ]; then
	exit 1
fi

VIDEO_SUBFIX=".mp4"
$REC_BIN $dir/$filename-audio.mjr $dir/$filename-audio.opus
degrees=$(env JANUS_PPREC_VIDEOORIENTEXT=4 $REC_BIN $dir/$filename-video.mjr $dir/$filename-video$VIDEO_SUBFIX | grep 'Video rotation' | awk 'END{print $3}')

if [ "$degrees" = "90" ]; then
	$FFMPEG_BIN -i $dir/$filename-audio.opus -i $dir/$filename-video$VIDEO_SUBFIX -c:a aac -vf "transpose=1" -strict experimental $DEST_DIR/$filename$VIDEO_SUBFIX
elif [ "$degrees" = "180" ]; then
	$FFMPEG_BIN -i $dir/$filename-audio.opus -i $dir/$filename-video$VIDEO_SUBFIX -c:a aac -vf "transpose=2,transpose=2" -strict experimental $DEST_DIR/$filename$VIDEO_SUBFIX
elif [ "$degrees" = "270" ]; then
	$FFMPEG_BIN -i $dir/$filename-audio.opus -i $dir/$filename-video$VIDEO_SUBFIX -c:a aac -vf "transpose=2" -strict experimental $DEST_DIR/$filename$VIDEO_SUBFIX
else
	$FFMPEG_BIN -i $dir/$filename-audio.opus -i $dir/$filename-video$VIDEO_SUBFIX -c:a aac -strict experimental $DEST_DIR/$filename$VIDEO_SUBFIX
fi

rm -rf $dir/$filename-audio.opus $dir/$filename-video$VIDEO_SUBFIX $dir/$filename-audio.mjr $dir/$filename-video.mjr
NOTIFY_URL=http://61.185.204.73:8090/TPRI_DMP_MobileBus/services/hostcomputer/saveVideoUrl?json={\"businessInfo\":{\"businessModel\":\"$business_model\",\"businessId\":\"$business_id\"'}',\"videoUrl\":\"$DEST_DIR/$filename$VIDEO_SUBFIX\"'}'

echo $NOTIFY_URL
curl -g --url "$NOTIFY_URL" --max-time 3

exit 0
